<template>
  <!-- 视频播放页 -->
  <div class="video_playback_page">
    <NavBar title="" :showPlaceholder="false">
      <template #left>
        <Icon name="zuojiantou" size="20" color="#fff" @click="isShowVideoFn" />
      </template>
    </NavBar>

    <!-- 视频轮播 -->
    <Swipe ref="swipeRef" v-if="videoList.length" :height="667" :showIndicators="false" @change="handleSwipeChange">
      <SwipeItem v-for="(item, index) in videoList" :key="item.Video?.videoId || index">
        <!-- 视频播放器 -->
        <CustomVideo :src="item.Video?.videoPath" :active="currentIndex === index" @dbltap="handleDoubleTap(index)" />

        <!-- 左侧：视频信息 -->
        <template #left>
          <div class="video_intro">
            <div class="video_intro__city">北京市</div>
            <div class="video_intro__username">@{{ item.Video?.userNickname }}</div>
            <div class="video_intro__desc">{{ item.Video?.videoDesc }}</div>
          </div>
        </template>

        <!-- 右侧：操作按钮 -->
        <template #right>
          <div class="video_operation">
            <!-- 用户头像 -->
            <div class="video_operation__item">
              <img :src="item.Video?.userAvatar ? 'http://43.138.15.137:3000' + item.Video.userAvatar : ''" alt="" />
              <Icon class="jia-icon" name="jia" size="20" color="#fff" />
            </div>

            <!-- 点赞 -->
            <div class="video_operation__item" @click="handleLike(item.Video?.userId, item.Video?.videoId, index)">
              <div class="like-wrapper" :class="{ animated: item.animated }">
                <Icon name="xin-2" size="32" :color="isLiked(item.WSLCNum?.likeList) ? '#FF4D4F' : '#fff'" />
              </div>
              <span>{{ item.WSLCNum?.likeNum }}</span>
            </div>

            <!-- 评论 -->
            <div class="video_operation__item" @click="handleComment(item.Video?.videoId, index)">
              <Icon name="pinglun" size="32" color="#fff" />
              <span>{{ item.WSLCNum?.commentNum }}</span>
            </div>

            <!-- 分享 -->
            <div class="video_operation__item">
              <Icon name="a-fenxiangweifenxiang" size="24" color="#fff" />
              <span>{{ item.WSLCNum?.shareNum }}</span>
            </div>
          </div>
        </template>
        <!-- 输入框 -->
        <div class="input_bar">
          <!-- 获焦事件 -->
          <input type="text" placeholder="有爱评论，说点儿好听的~（长按评论回复）" @focus="handleComment(item.Video?.videoId, index)">
          <div class="input_bar_icon" @click="handleComment(item.Video?.videoId, index)">
            <Icon name="aite" size="18" color="#fff" />
          </div>
          <div class="input_bar_icon" @click="handleComment(item.Video?.videoId, index)">
            <Icon name="dui" size="18" color="#fff" />
          </div>
        </div>
      </SwipeItem>
    </Swipe>
    <!--  评论弹窗 -->
    <Commentcomponent v-model="isShowComment" :commentList="commentList" @newComment="handleNewComment"
      :videoId="currentVideoId" />

  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, defineAsyncComponent } from 'vue'
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import Swipe from '@/components/Common/Swipe/index.vue'
import SwipeItem from '@/components/Common/SwipeItem/index.vue'
import CustomVideo from '@/components/Common/CustomVideo/index.vue'
import { useUserStore } from '@/stores/userStatus'
const userStore = useUserStore()
// 双向绑定关闭
const model = defineModel()
const isShowVideoFn = () => (model.value = false)

// 接收数据：必须是 { list: [...], initialIndex: number }
const props = defineProps({
  data: {
    type: Object,
    default: () => ({ list: [], initialIndex: 0 })
  }
})
console.log('接收数据:', props.data)

const videoList = computed(() => props.data.list || [])
const currentIndex = ref(0)
const swipeRef = ref(null) // 引用 Swipe 组件

// 跳转到指定索引
const goToInitialIndex = () => {
  const index = props.data.initialIndex ?? 0;
  console.log('尝试跳转到索引:', index, '视频列表长度:', videoList.value.length);

  if (index < 0 || index >= videoList.value.length) {
    console.log('索引超出范围');
    return;
  }

  // 先更新 currentIndex，确保视频组件状态正确
  currentIndex.value = index;

  let attempts = 0;
  const tryGoTo = () => {
    const swipe = swipeRef.value;
    console.log('尝试调用 goTo, swipe:', swipe, 'attempts:', attempts);

    if (!swipe || typeof swipe.goTo !== 'function') {
      console.log('Swipe 组件未准备好或没有 goTo 方法');
      attempts++;
      if (attempts < 10) {
        setTimeout(tryGoTo, 100);
      }
      return;
    }

    // 调用 goTo 方法，禁用过渡动画
    try {
      swipe.goTo(index, true); // 传入 true 表示不使用过渡动画
      console.log('成功调用 goTo 方法，索引:', index);
    } catch (error) {
      console.error('调用 goTo 方法出错:', error);
      attempts++;
      if (attempts < 10) {
        setTimeout(tryGoTo, 100);
      }
    }
  };

  tryGoTo();
}

// 监听 data 变化（支持多次打开不同视频）
watch(
  () => props.data,
  (newData) => {
    if (!newData || !newData.list || newData.list.length === 0) return;

    // 直接设置初始索引，不要先设为0
    const initialIndex = newData.initialIndex ?? 0;
    console.log('设置初始索引:', initialIndex);

    // 使用 nextTick 确保 DOM 已更新
    nextTick(() => {
      // 增加延迟时间，确保 Swipe 组件完全初始化
      setTimeout(() => {
        goToInitialIndex();
      }, 200);
    });
  },
  { immediate: true }
)

// 处理滑动切换
const handleSwipeChange = (index) => {
  currentIndex.value = index
}

// 双击处理（可选）
const handleDoubleTap = (index) => {
  console.log('双击视频:', index)
}
const isLiked = (likeList) => {
  // 临时使用固定用户ID进行测试，实际应用中应从userStore获取
  const currentUserId = userStore.userInfo?.userId || 1; // 默认使用用户ID为1进行测试
  return Array.isArray(likeList) && likeList.includes(currentUserId)
}

// 点赞、评论等方法（保留原有逻辑）
const handleLike = async (userId, videoId, index) => {
  console.log('1')
  if (!userId || !videoId || index === undefined) return

  const videoItem = videoList.value[index]
  if (!videoItem || videoItem.isLiking) return // 防抖：正在点赞中，阻止重复触发

  const currentUserId = userStore.userInfo?.userId || 1

  // 确保 WSLCNum 对象存在
  if (!videoItem.WSLCNum) {
    videoItem.WSLCNum = { likeNum: 0, likeList: [] }
  }

  // 确保 likeList 是数组
  if (!Array.isArray(videoItem.WSLCNum.likeList)) {
    videoItem.WSLCNum.likeList = []
  }

  // 设置防抖状态
  videoItem.isLiking = true

  // 记录当前是否已点赞（用于后续判断）
  const isCurrentlyLiked = isLiked(videoItem.WSLCNum.likeList)

  // 1. 播放动画
  videoItem.animated = true

  // 2. 本地立即更新状态
  if (isCurrentlyLiked) {
    videoItem.WSLCNum.likeList = videoItem.WSLCNum.likeList.filter(id => id !== currentUserId)
    videoItem.WSLCNum.likeNum--
  } else {
    videoItem.WSLCNum.likeList = [...videoItem.WSLCNum.likeList, currentUserId]
    videoItem.WSLCNum.likeNum++
  }

  // 3. 重置动画
  setTimeout(() => {
    videoItem.animated = false
  }, 600)

  // 发送请求（无论成功失败，最终都要释放锁定）
  try {
    await likeAPI(userId, videoId)
    // 此处可更新 likeList 来自服务器的最新状态（可选）
  } catch (error) {
    console.error('点赞失败，尝试回滚')

    // 回滚 UI 状态
    if (isCurrentlyLiked) {
      videoItem.WSLCNum.likeList = [...videoItem.WSLCNum.likeList, currentUserId]
      videoItem.WSLCNum.likeNum++
    } else {
      videoItem.WSLCNum.likeList = videoItem.WSLCNum.likeList.filter(id => id !== currentUserId)
      videoItem.WSLCNum.likeNum--
    }
  } finally {
    // 在 try...catch...finally 后面加
    setTimeout(() => {
      if (videoItem.isLiking) {
        videoItem.isLiking = false // 强制释放
        console.warn('防抖超时强制释放')
      }
    }, 800)
  }
}



// 导入评论弹窗组件
const Commentcomponent = defineAsyncComponent(() => import('@/views/home/Commentcomponent/index.vue'))
import { getHomeVideoListAPI, likeAPI, commentAPI, commentLikeAPI } from '@/api/Home'

// 评论弹窗状态
const isShowComment = ref(false)
const commentList = ref([])
const currentVideoId = ref('')
import { useUserIDStore } from '@/stores/UserID'
const userIDStore = useUserIDStore()

// 处理新评论
const handleNewComment = (newComment) => {
  newComment.Comment.createdAt = newComment.Comment.createdAt
  // 添加到最前面
  commentList.value.unshift(newComment)
  console.log('更新后的评论列表:', commentList.value)
}
const handleComment = async (videoId, index) => {
  if (!videoId || index === undefined) return

  currentVideoId.value = videoId

  try {
    const res = await commentAPI(videoId)
    if (res.code === 200) {
      // 只保留原始数据，不格式化时间
      commentList.value = res.data.map(item => ({
        ...item,
        Comment: {
          ...item.Comment,
          createdAt: item.Comment.createdAt // 原始时间戳（毫秒）
        }
      }))
      isShowComment.value = true

      // 单独处理点赞状态
      const userId = userIDStore.userInfo?.userId
      if (userId) {
        commentList.value.forEach(async (item) => {
          const res = await commentLikeAPI(userId, item.Comment.commentId)
          if (res.code === 200) {
            item.Comment.isLiked = res.data
          }
        })
      }
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

</script>

<style lang="scss" scoped>
.video_playback_page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #161622;
  z-index: 999;

  .input_bar {
    width: 100%;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    height: 44px;
    position: absolute;
    bottom: 0;
    background: #1a1b20;

    input {
      background: #1a1b20;
      -webkit-box-flex: 1;
      -ms-flex: 1;
      flex: 1;
      font-size: 14px;
      color: #e8e8e9;
      padding-left: 10px;
      caret-color: #face15;
    }

    .input_bar_icon {
      width: 44px;
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;

    }
  }
}
</style>